const user = require('../models/user')
const md5 = require('../utils/md5')


var xlsx = require('xlsx');
/**
 * 
 * 测试用学生注册
 * 
 */
var studentRes = async (ctx,next)=>{
    let document = await user.findOne({account:ctx.request.body.account});
    if(document){
        return ctx.response.body = {stauts:'error',msg:'用户已存在'};
    }
    var account = ctx.request.body.account;
    var password = md5(ctx.request.body.password);
    var name = ctx.request.body.name;
    var course1 = ctx.request.body.course1;
    var course2 = ctx.request.body.course2;
    var course3 = ctx.request.body.course3;
    var course = [course1,course2,course3]

    var userEntity = new user({
        account:account,
        password:password,
        name:name,
        course:course
    })
    userEntity.save(function(err,doc){
        if(err){
            console.log(err);
        }else{
            console.log(doc);
        }
    })
    password = null;
    return ctx.response.body = {stauts:'success',msg:'成功',userEntity};

}

/**
 * 
 * 测试用老师注册
 * 
 */


var register = async (ctx,next) => {


        let document = await user.findOne({account:ctx.request.body.account});
        if(document){
            return ctx.response.body = {stauts:'error',msg:'用户已存在'};
        }
        var account = ctx.request.body.account;
        var password = md5(ctx.request.body.password);
        var course1 = ctx.request.body.course1;
        var class1_1 = ctx.request.body.class1_1
        var class1_2 = ctx.request.body.class1_2
        var course2 = ctx.request.body.course2
        var class2_1 = ctx.request.body.class2_1
        var course = {course1:[course1,class1_1,class1_2],course2:[course2,class2_1]}

        var userEntity = new user({
            account:account,
            password:password,
            course:course
        })
        userEntity.save(function(err,doc){
            if(err){
                console.log(err);
            }else{
                console.log(doc);
            }
        })
        password = null;
        return ctx.response.body = {stauts:'success',msg:'成功',userEntity};

}

var moreregister = async (ctx,next)=>{


    if(typeof require !== 'undefined')XLSX=require('xlsx');
    let workbook = XLSX.readFile('./controllers/bb.xlsx');
    let sheet_name_list = workbook.SheetNames;
    let x=0,y=2;

    let account,name,password,c,course=new Array(),registered=new Array();
    for(sheetname of sheet_name_list) { /* iterate through sheets */
        var worksheet = workbook.Sheets[sheetname];
        for (z in worksheet) {


            /* 带!的属性（比如!ref）是表格的特殊属性，用来输出表格的信息，不是表格的内容，所以去掉 */
           if(z[1] === '!') continue;

            // console.log(sheetname + ": " + z + "=" + JSON.stringify(worksheet[z].v));
            if(z.indexOf(y)==1){
                if(z.indexOf('A')==0){
                    account=worksheet[z].v

                }
                if(z.indexOf('B')==0){
                    name=worksheet[z].v

                }
                if(z.indexOf('C')==0){
                    password=JSON.stringify(worksheet[z].v)

                }

                // if(z.indexOf('D')==0){
                //     c=worksheet[z].v
                //     c=new Array()
                //     console.log(c)
                // }
                // if(z.indexOf('E')==0){
                //     console.log('E')
                // }
                // if(z.indexOf('F')==0){
                //     console.log('F')
                // }
                // if(z.indexOf('G')==0){
                //     console.log('G')
                // }
              console.log(worksheet[z].v);
                x++

            };


            if(x==3){
                x=0;
                y++;
                //判断用户是否存在
                let document = await user.findOne({account:account});
                console.log(document)
                if(document) {
                    //存在则放进数组一起放回
                    registered.push(account)
                    continue;
                }

                var userEntity = new user({
                    account:account,
                    password:md5(password),
                    name:name,
                });
                userEntity.save(function(err,doc){
                    if(err){
                        console.log(err);
                    }else{
                        console.log(doc);
                    }
                })
                //不存在则注册
                // var userEntity = new user({
                //     account:account,
                //     password:password,
                //     name:name,
                // });
                // userEntity.save(function(err,doc){
                //     if(err){
                //         console.log(err);
                //     }else{
                //         console.log(doc);
                //     }
                // })

                console.log("/n");
            }
        }
        return ctx.response.body = {stauts:'error',msg:'已注册用户',registered};

    };
}


/**
 * 
 * 登录
 * 成功时返回用户信息signin_user
 * 
 */
var signin = async (ctx,next) => {
    let signin_user = await user.findOne({account:ctx.request.body.account})
    if(signin_user){
        if(md5(ctx.request.body.password) === signin_user.password){
            signin_user.password = null;
            // ctx.session.user = signin_user;
            return ctx.response.body = {stauts:'success',msg:'成功',signin_user};
        }
        return ctx.response.body = {stauts:'error',msg:'密码错误',signin_user};
    }
    return ctx.response.body = {stauts:'error',msg:'用户未注册',signin_user};
}
/**
 * 
 * 修改密码
 * 成功时返回用户信息signin_user
 * 
 */
var repassword = async (ctx,next)=>{
        let signin_user = await user.findOne({account:ctx.request.body.account})
        let userID = signin_user._id;
        if(signin_user){
            if(md5(ctx.request.body.password) === signin_user.password){
                user.findByIdAndUpdate(userID,{$set:{password:md5(ctx.request.body.repassword)}},function(err,user){
                    console.log(err);
                })
                signin_user.password = null;
                return ctx.response.body = {stauts:'success',msg:'成功',signin_user};
            }
            return ctx.response.body = {stauts:'error',msg:'密码错误',signin_user};
        }
        return ctx.response.body = {stauts:'error',msg:'用户未注册',signin_user};
}
/**
 * 
 * 登出
 * 
 */

var signout = async (ctx,next)=>{
    let signout_user = {};
    return ctx.response.body = {stauts:'success',msg:'成功',signout_user};
}

var test = async (ctx,next)=>{
    console.log(ctx.request.body)
}
/**
 * 
 * 获取用户数据
 * 
 */
var getuser = async (ctx,next)=>{
    let signin_user = await user.findOne({account:ctx.request.body.account})
    signin_user.password = null;
    return ctx.response.body = {stauts:'success',msg:'成功',signin_user};
}

/**
 * 
 * 提交实验（局部修改）
 * 
 */
var commitEx = async (ctx,next)=>{
    try{
        let signUser = await user.findOne({account:ctx.request.body.account})
        signUser.password = null;
        let userId = signUser._id;
        let answer = ctx.request.body.answer;
        let title = ctx.request.body.title;
        if(signUser.experiment==[]){

        }else{
            for(var e of signUser.experiment){
                if(e[0]==title){
                    await user.findByIdAndUpdate(userId,{$pull:{experiment:[title,e[1]]}},function(err,user){
                        console.log(err);
                    })
                    await user.findByIdAndUpdate(userId,{$push:{experiment:[title,answer]}},function(err,user){
                        console.log(err);
                    })
                    console.log(await user.findOne({account:ctx.request.body.account}))
                    return ctx.response.body = {stauts:'success',msg:'修改成功'};
                }
            }
        }
        await user.findByIdAndUpdate(userId,{$push:{experiment:[title,answer]}},function(err,user){
            console.log(err);
        })
        console.log(await user.findOne({account:ctx.request.body.account}))
        return ctx.response.body = {stauts:'success',msg:'提交成功'};
    }catch(err){
        console.log(err)
    }
    

}
module.exports = {
    'POST /user/register': register,
    'POST /user/signin': signin,
    'POST /user/repassword': repassword,
    'POST /user/signout' : signout,
    'POST /user/test' : test,
    'GET /user/moreregister':moreregister,
    'POST /user' : getuser,
    'POST /user/studentRes' : studentRes,
    'POST /user/commitEx' : commitEx,
}